#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

#include "uvbotlib.h"

int roll(int sides)
{
    return rand() % sides + 1;
}

// getFacingSq FIND TERRAIN IN DIRECTION BOT IS FACING
// INDEXES INTO MAP STRING GO INTO SQUARE LIKE THIS:
//  0 1 2 
//  3 4 5
//  6 7 8
// WHERE 4 IS THE SQUARE THE BOT IS OCCUPYING

char getFacingSq(BotStatus& status)
{
    int indexes[] = {1, 2, 5, 8, 7, 6, 3, 0};
    int face;
    char terrain;

    face = (status.getFacing() + 23) / 45;
    if (face > 7) 
	{  // VALID VALUES ARE 0 THROUGH 7
		face = 0;
    }
    terrain = status.getMap()[indexes[face]];
    cout << "getFacingSq facing: " << status.getFacing() 
	 << " face: " << face
	 << " index: " << indexes[face] 
	 << " terrain: " << terrain 
	 << endl;
    return terrain;
}

string makeCmd(BotStatus& status)
{
    int die;
    string cmd;
    char terrain;

	Scan tmp2;
	Scan tmp3;

    terrain = getFacingSq(status);
	int fireAngle = 0;
	bool fire = false;
	bool random = false;
	for( int i = 0; i < status.getScanCount(); i ++)
	{
		tmp2 = status.getScan(i);
		int id = tmp2.getId();
		fire = true;
		fireAngle = status.getAngle(status.getLoc(), tmp2.getLoc());
		random = true;
		char buffer[20];
		sprintf_s (buffer, "fire %d", fireAngle);
		string cmdString(buffer);
		cmd = cmdString;
	}
	if (!random)
	{
		die = roll(6);
		switch(die) 
		{
			case 1:
			case 2:
			cmd = "move 0";
			break;
			case 3:
			cmd = "move 45";
			break;
			case 4:
			cmd = "move -45";
			break;
			case 5:
			cmd = "turn 90";
			break;
			case 6:
			cmd = "turn -90";
			break;
			default:
			cmd = "move 0";
			break;
		}
    }
    return cmd;
}

int main(int argc, char** argv)
{
    UvBot bot;
    BotStatus status;
    string cmd, result;
    ConnectionWin conn;
    string hostName, name;
    int port;
    bool destroyed = false;
    
    srand(time(NULL));

    hostName = "localhost";
    port = 4688;

    if (argc > 1) 
	{
        name = argv[1];
    }

    if (argc > 2) 
	{
		port = atoi(argv[2]);
    }

    if (argc > 3) 
	{
		hostName = argv[3];
    }

    bot.connect(hostName, port, name);

	cmd = "TURN 90";         // BLD 28NOV07
	result = bot.doCmd(cmd); // BLD 28NOV07
	status.parse(result);    // BLD 28NOV07

    while (!destroyed) 
	{
		cmd = makeCmd(status);
		cout << "CMD: " << cmd << endl;
		result = bot.doCmd(cmd);
		cout << result << endl;
		status.parse(result);
		cout << "Done parsing result" << endl;
	}
    cout << "Destroyed" << endl;
	return 0;
}

